<template>
  <section class='f-change-phone'>
    <van-form ref="ruleFormRef" @submit="onSubmit" input-align="right" error-message-align="right">
      <van-cell-group>
        <van-field v-model="userInfo.phone" label="当前号码" type="tel" readonly></van-field>

        <van-field v-model="form.newPhone" clearable name="newPhone" label="更改号码" placeholder="请输入新的手机号码" type="tel"
          maxlength="11" :rules="[{ required: true, message: '请输入新的手机号码' },{ pattern: /^1[3-9]\d{9}$/, message: '请填写正确的手机号码'}]">
        </van-field>

        <van-field v-model="form.verificationCode" clearable name="verificationCode" label="验证码" placeholder="请输入验证码"
          type="number" maxlength="6" :rules="[{ required: true, message: '请填写验证码' }]">
          <template #button>
            <van-button size="small" type="primary" @click="getMsgCodeHandle">{{count? count + '秒': '获取验证码'}}</van-button>
          </template>
        </van-field>

        <van-field v-model="form.password" clearable name="password" label="密码验证" placeholder="请输入登录密码"
          :type="form.showPassword?'':'password'" :rules="[{ required: true, message: '请输入登录密码' }]">
          <template #right-icon>
            <van-icon v-show="!form.showPassword" name="closed-eye" @click="form.showPassword = true" />
            <van-icon v-show="form.showPassword" name="eye-o" @click="form.showPassword = false" />
          </template>
        </van-field>

      </van-cell-group>
      <div class="f-submit-btn">
        <van-button round block type="primary" native-type="submit">确定</van-button>
      </div>
    </van-form>
  </section>
</template>
  <script>
import { ref, reactive, toRefs, onMounted, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex';
import api from '../api'
import { successDeal, getStore, removeStore } from '@/utils/utils';
import { showDialog } from 'vant';
import hexMD5 from "@/utils/md5.min.js"

export default {
  setup(props, context) {
    const store = useStore()

    const router = useRouter()
    const route = useRoute();

    const ruleFormRef = ref()

    const state = reactive({
      userInfo: getStore('USER_INFO'),
      form: {
        newPhone: ''
      },

      counter: 0, // 计时器
      count: 0,
      phone: '',
    })

    onMounted(() => {
      store.commit("setNavBar", {
        title: '更换手机号码',
        show: true,
        left: true,
        leftType: 'back',
        right: false,
        rightType: 'search',
      });
    })


    // 获取短信验证码
    const getMsgCodeHandle = () => {
      if (state.count) return
      ruleFormRef.value.validate(['newPhone']).then(res => {
        state.count = 120;
        countDown();

        let json = {
          "phone": state.form.newPhone,
          "smsWay": "modify",
          "source": "android",
          "verificationCode": ""
        }
        api.getSmsForModifyPhone(json).then((res) => {
          successDeal('短信已发送！')
        }).catch(err => {
          state.count = 0
          clearCounter()
        })
      })
    }

    //计时
    const countDown = () => {
      let count = state.count;

      clearCounter();
      state.counter = setInterval(() => {
        count--;
        state.count = count;
        if (count == 0) {
          clearCounter();
        }
      }, 1000);
    }

    //清除定时器
    const clearCounter = () => {
      clearInterval(state.counter);
    }

    const onSubmit = () => {
      let data = JSON.parse(JSON.stringify(state.form))
      let json = {
        "newPhone": data.newPhone,
        "password": hexMD5(data.password),
        "source": 'android',
        "verificationCode": data.verificationCode,
      }
      api.updatePhone(json).then(res => {
        removeStore('USER_ACCONT')
        removeStore('USER_INFO')

        showDialog({
          title: '提示',
          message: '更换手机号码成功，请重新登录！',
        }).then(() => {
          router.replace('/')
        });
      })
    }

    return {
      ...toRefs(state),
      ruleFormRef,
      getMsgCodeHandle,
      onSubmit,
    }
  }
}
  </script>
  <style lang='scss' scoped>
.f-change-phone {
  .f-submit-btn {
    margin-top: 70px;
    padding: 0 62px;
  }
  :deep(.van-nav-bar__title) {
    color: #fff;
  }
  :deep(.van-nav-bar .van-icon) {
    color: #fff;
  }
}
</style>